package com.bj58.mis.apm.server.logreceiver.service.impl;

import com.bj58.mis.apm.server.logreceiver.model.DictionaryItem;
import com.bj58.mis.apm.server.logreceiver.model.DictionaryType;
import com.bj58.mis.apm.server.logreceiver.repository.DictionaryItemRepository;
import com.bj58.mis.apm.server.logreceiver.repository.DictionaryTypeRepository;
import com.bj58.mis.apm.server.logreceiver.service.DictionaryService;
import com.bj58.mis.apm.server.logreceiver.vo.DictionaryItemVO;
import com.bj58.mis.apm.server.logreceiver.vo.DictionaryTypeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: wangxw
 * @Date: 2018/8/20 17:32
 */
@Service
public class DictionaryServiceImpl implements DictionaryService {

    @Autowired
    private DictionaryTypeRepository typeRepository;
    @Autowired
    private DictionaryItemRepository itemRepository;

    @Override
    public List<DictionaryTypeVO> queryTypes() {
        return typeRepository.findAll().stream().map(type -> getDictionaryTypeVO(type)).collect(Collectors.toList());
    }

    @Override
    public List<DictionaryItemVO> queryItems(String typeName) {
        return itemRepository.queryByDictionaryTypeOrderByDictionaryItemSort(typeName).stream().map(item -> getDictionaryItemVO(item)).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void saveItems(List<DictionaryItemVO> itemList) {
        itemRepository.deleteAll(itemList.stream().filter(vo -> vo.getDictionaryItemId() != null && vo.isDelete()).map(vo -> getDictionaryItem(vo, itemList.indexOf(vo))).collect(Collectors.toList()));
        itemRepository.saveAll(itemList.stream().filter(vo -> !vo.isDelete()).map(vo -> getDictionaryItem(vo, itemList.indexOf(vo))).collect(Collectors.toList()));
    }

    DictionaryTypeVO getDictionaryTypeVO(DictionaryType type){
        DictionaryTypeVO vo = new DictionaryTypeVO();
        BeanUtils.copyProperties(type, vo);
        return vo;
    }
    DictionaryItemVO getDictionaryItemVO(DictionaryItem item){
        DictionaryItemVO vo = new DictionaryItemVO();
        BeanUtils.copyProperties(item, vo);
        return vo;
    }
    DictionaryItem getDictionaryItem(DictionaryItemVO vo, int index){
        DictionaryItem item = new DictionaryItem();
        BeanUtils.copyProperties(vo, item);
        item.setDictionaryItemSort(index + 1L);
        return item;
    }
}
